package com.gxuwz.leave.servlet;

import com.gxuwz.leave.context.AppContext;
import com.gxuwz.leave.service.InstService;
import com.gxuwz.leave.service.StuService;
import com.gxuwz.leave.service.UserService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends BaseHttpServlet{
    private final static String VIEW_LOGIN = "login.jsp";
    private final static String ACTION_MAIN = "/index";

    private UserService userService;
    private InstService instService;

    private StuService stuService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doDispatch(req, resp, VIEW_LOGIN);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userid =req.getParameter("userid");
        String password =req.getParameter("password");
        String identity =req.getParameter("identity");
        try{
            boolean flag;
            //根基身份验证用户+密码的合法性
            if("user".equals(identity)){
                flag = userService.checkUser(userid,password);
            }else if("instructor".equals(identity)){
                flag = instService.checkInst(userid,password);
            }else if("student".equals(identity)){
                flag = stuService.checkStu(userid, password);
            }else {
                return;
            }
            if (flag){
                req.getSession().setAttribute("userID", userid);
                req.getSession().setAttribute("identity", identity);
                // 登录成功，重定向到主页
                super.doRedirect(req,resp,req.getContextPath()+ACTION_MAIN);
            }else{
                super.doDispatch(req,resp,VIEW_LOGIN);
            }
        }catch (Exception e){
            e.printStackTrace();
            super.doRedirect(req,resp,req.getContextPath()+ErrorPage_500);
        }
        //3:返回响应报文
    }
    @Override
    public void init() throws ServletException {
        super.init();
        //从IoC容器获取实例化bean组件
        userService= AppContext.getBean(UserService.class);
        instService= AppContext.getBean(InstService.class);
        stuService = AppContext.getBean(StuService.class);
    }
}
